import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class SalesManageFrame extends JFrame {
    private JTable salesTable;
    private DefaultTableModel tableModel;

    public SalesManageFrame() {
        setTitle("销售管理");
        setSize(1000, 600);
        setLocationRelativeTo(null);

        // 表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("销售单号");
        tableModel.addColumn("销售日期");
        tableModel.addColumn("货物编号");
        tableModel.addColumn("货物名称");
        tableModel.addColumn("销售数量");
        tableModel.addColumn("销售价格");
        tableModel.addColumn("客户编号");
        tableModel.addColumn("客户名称");
        tableModel.addColumn("销售员");

        salesTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(salesTable);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addBtn = new JButton("添加销售");
        JButton deleteBtn = new JButton("删除记录");
        JButton refreshBtn = new JButton("刷新");

        buttonPanel.add(addBtn);
        buttonPanel.add(deleteBtn);
        buttonPanel.add(refreshBtn);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        loadSalesData();

        // 事件监听
        addBtn.addActionListener(e -> {
            new SalesEditDialog(null).setVisible(true);
            loadSalesData();
        });

        deleteBtn.addActionListener(e -> deleteSales());
        refreshBtn.addActionListener(e -> loadSalesData());
    }

    private void loadSalesData() {
        tableModel.setRowCount(0);

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(
                     "SELECT s.sno, s.sdate, s.dno, g.dname, s.snum, s.sprice, " +
                             "s.cno, c.cname, sa.sname " +
                             "FROM sales s JOIN goods g ON s.dno = g.dno " +
                             "JOIN customer c ON s.cno = c.cno " +
                             "JOIN sale sa ON s.sale_no = sa.sno")) {

            while (rs.next()) {
                tableModel.addRow(new Object[]{
                        rs.getString("sno"),
                        rs.getDate("sdate"),
                        rs.getString("dno"),
                        rs.getString("dname"),
                        rs.getInt("snum"),
                        rs.getBigDecimal("sprice"),
                        rs.getString("cno"),
                        rs.getString("cname"),
                        rs.getString("sname")
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteSales() {
        int selectedRow = salesTable.getSelectedRow();
        if (selectedRow >= 0) {
            String sno = (String) tableModel.getValueAt(selectedRow, 0);

            int confirm = JOptionPane.showConfirmDialog(
                    this,
                    "确定要删除销售单 " + sno + " 吗?",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement pstmt = conn.prepareStatement("DELETE FROM sales WHERE sno = ?")) {

                    pstmt.setString(1, sno);
                    int affectedRows = pstmt.executeUpdate();

                    if (affectedRows > 0) {
                        JOptionPane.showMessageDialog(this, "删除成功");
                        loadSalesData();
                    }
                } catch (SQLException e) {
                    JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的行", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}

class SalesEditDialog extends JDialog {
    private JTextField snoField, snumField, spriceField;
    private JComboBox<String> goodsCombo, customerCombo, salesPersonCombo;
    private JSpinner sdateSpinner;
    private boolean isEditMode;
    private DefaultComboBoxModel<String> goodsModel, customerModel, salesPersonModel;

    public SalesEditDialog(String sno) {
        if (sno == null) {
            setTitle("添加销售单");
            isEditMode = false;
        } else {
            setTitle("修改销售单");
            isEditMode = true;
        }

        setSize(600, 400);
        setModal(true);
        setLocationRelativeTo(null);

        // 初始化模型
        goodsModel = new DefaultComboBoxModel<>();
        customerModel = new DefaultComboBoxModel<>();
        salesPersonModel = new DefaultComboBoxModel<>();
        loadComboData();

        JPanel panel = new JPanel(new GridLayout(7, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(new JLabel("销售单号:"));
        snoField = new JTextField();
        if (isEditMode) snoField.setEditable(false);
        panel.add(snoField);

        panel.add(new JLabel("销售日期:"));
        sdateSpinner = new JSpinner(new SpinnerDateModel());
        JSpinner.DateEditor dateEditor = new JSpinner.DateEditor(sdateSpinner, "yyyy-MM-dd");
        sdateSpinner.setEditor(dateEditor);
        panel.add(sdateSpinner);

        panel.add(new JLabel("货物:"));
        goodsCombo = new JComboBox<>(goodsModel);
        panel.add(goodsCombo);

        panel.add(new JLabel("销售数量:"));
        snumField = new JTextField();
        panel.add(snumField);

        panel.add(new JLabel("销售价格:"));
        spriceField = new JTextField();
        panel.add(spriceField);

        panel.add(new JLabel("客户:"));
        customerCombo = new JComboBox<>(customerModel);
        panel.add(customerCombo);

        panel.add(new JLabel("销售员:"));
        salesPersonCombo = new JComboBox<>(salesPersonModel);
        panel.add(salesPersonCombo);

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> saveSales());

        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        add(panel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        if (isEditMode) {
            loadSalesData(sno);
        } else {
            // 新建时默认日期为当天
            sdateSpinner.setValue(new java.util.Date());
        }
    }

    private void loadComboData() {
        // 加载货物数据
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT dno, dname FROM goods")) {
            while (rs.next()) {
                goodsModel.addElement(rs.getString("dname") + " (" + rs.getString("dno") + ")");
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载货物数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }

        // 加载客户数据
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT cno, cname FROM customer")) {
            while (rs.next()) {
                customerModel.addElement(rs.getString("cname") + " (" + rs.getString("cno") + ")");
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载客户数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }

        // 加载销售员数据
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT sno, sname FROM sale")) {
            while (rs.next()) {
                salesPersonModel.addElement(rs.getString("sname") + " (" + rs.getString("sno") + ")");
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载销售员数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void loadSalesData(String sno) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(
                     "SELECT s.*, g.dname, c.cname, sa.sname FROM sales s " +
                             "JOIN goods g ON s.dno = g.dno " +
                             "JOIN customer c ON s.cno = c.cno " +
                             "JOIN sale sa ON s.sale_no = sa.sno " +
                             "WHERE s.sno = ?")) {

            pstmt.setString(1, sno);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                snoField.setText(rs.getString("sno"));
                sdateSpinner.setValue(rs.getDate("sdate"));
                snumField.setText(String.valueOf(rs.getInt("snum")));
                spriceField.setText(rs.getBigDecimal("sprice").toString());

                // 设置选中的货物
                String goodsText = rs.getString("dname") + " (" + rs.getString("dno") + ")";
                goodsCombo.setSelectedItem(goodsText);

                // 设置选中的客户
                String customerText = rs.getString("cname") + " (" + rs.getString("cno") + ")";
                customerCombo.setSelectedItem(customerText);

                // 设置选中的销售员
                String salesPersonText = rs.getString("sname") + " (" + rs.getString("sale_no") + ")";
                salesPersonCombo.setSelectedItem(salesPersonText);
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载销售数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void saveSales() {
        String sno = snoField.getText().trim();
        java.util.Date sdate = (java.util.Date) sdateSpinner.getValue();
        String snumStr = snumField.getText().trim();
        String spriceStr = spriceField.getText().trim();

        // 从组合框中提取ID
        String goodsSelected = (String) goodsCombo.getSelectedItem();
        String dno = goodsSelected.substring(goodsSelected.lastIndexOf("(") + 1, goodsSelected.lastIndexOf(")"));

        String customerSelected = (String) customerCombo.getSelectedItem();
        String cno = customerSelected.substring(customerSelected.lastIndexOf("(") + 1, customerSelected.lastIndexOf(")"));

        String salesPersonSelected = (String) salesPersonCombo.getSelectedItem();
        String sale_no = salesPersonSelected.substring(salesPersonSelected.lastIndexOf("(") + 1, salesPersonSelected.lastIndexOf(")"));

        // 验证输入
        if (sno.isEmpty() || snumStr.isEmpty() || spriceStr.isEmpty()) {
            JOptionPane.showMessageDialog(this, "所有字段都必须填写", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        int snum;
        double sprice;
        try {
            snum = Integer.parseInt(snumStr);
            if (snum <= 0) {
                JOptionPane.showMessageDialog(this, "销售数量必须大于0", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            sprice = Double.parseDouble(spriceStr);
            if (sprice <= 0) {
                JOptionPane.showMessageDialog(this, "销售价格必须大于0", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "销售数量和价格必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            PreparedStatement pstmt;

            if (isEditMode) {
                pstmt = conn.prepareStatement(
                        "UPDATE sales SET sdate=?, dno=?, snum=?, sprice=?, cno=?, sale_no=? WHERE sno=?");
                pstmt.setDate(1, new java.sql.Date(sdate.getTime()));
                pstmt.setString(2, dno);
                pstmt.setInt(3, snum);
                pstmt.setBigDecimal(4, new java.math.BigDecimal(sprice));
                pstmt.setString(5, cno);
                pstmt.setString(6, sale_no);
                pstmt.setString(7, sno);
            } else {
                pstmt = conn.prepareStatement(
                        "INSERT INTO sales (sno, sdate, dno, snum, sprice, cno, sale_no) " +
                                "VALUES (?, ?, ?, ?, ?, ?, ?)");
                pstmt.setString(1, sno);
                pstmt.setDate(2, new java.sql.Date(sdate.getTime()));
                pstmt.setString(3, dno);
                pstmt.setInt(4, snum);
                pstmt.setBigDecimal(5, new java.math.BigDecimal(sprice));
                pstmt.setString(6, cno);
                pstmt.setString(7, sale_no);
            }

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                JOptionPane.showMessageDialog(this, "保存成功");
                dispose();
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}